package com.dragon.modules.yuegou.client.wechat.client.impl;

import com.alibaba.fastjson.JSONObject;
import com.dragon.common.exception.DragonException;
import com.dragon.modules.yuegou.client.wechat.client.MiniClient;
import com.dragon.modules.yuegou.client.wechat.request.CreateRoomRequest;
import com.dragon.modules.yuegou.client.wechat.request.GoodsAddRequest;
import com.dragon.modules.yuegou.client.wechat.request.OpenidRequest;
import com.dragon.modules.yuegou.client.wechat.request.ReplayRequest;
import com.dragon.modules.yuegou.client.wechat.response.CreateRoomResponse;
import com.dragon.modules.yuegou.client.wechat.response.GetLiveResponse;
import com.dragon.modules.yuegou.client.wechat.response.GetgoodswarehouseResponse;
import com.dragon.modules.yuegou.client.wechat.response.GoodsAddResponse;
import com.dragon.modules.yuegou.client.wechat.response.MediaUploadResponse;
import com.dragon.modules.yuegou.client.wechat.response.OpenidResponse;
import com.dragon.modules.yuegou.client.wechat.response.ReplayResponse;
import com.dragon.modules.yuegou.client.wechat.response.UniteResponse;
import com.dragon.modules.yuegou.enums.code.LiveCode;
import com.dragon.modules.yuegou.enums.code.SystemCode;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MiniClientImpl implements MiniClient {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private WebClient client = WebClient.create("https://api.weixin.qq.com");

	private ObjectMapper objectMapper;

	public MiniClientImpl() {
		objectMapper = new ObjectMapper();
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	@Override
	public OpenidResponse jscode2session(OpenidRequest request) {
		String text = client.get()
				.uri(b -> b.path("/sns/jscode2session").queryParam("appid", request.getAppid())
						.queryParam("secret", request.getSecret()).queryParam("js_code", request.getJs_code())
						.queryParam("grant_type", request.getGrant_type()).build())
				.accept(MediaType.APPLICATION_JSON_UTF8).exchange().flatMap(res -> res.bodyToMono(String.class))
				.block();
		logger.debug("jscode2session : {}", text);
		try {
			return objectMapper.readerFor(OpenidResponse.class).readValue(text);
		} catch (IOException e) {
			logger.error(e.getMessage());
			throw new DragonException(SystemCode.WX_OPEN_ID_ERROR);
		}

	}

	@Override
	public MediaUploadResponse mediaUpload(String accessToken, String type, File file) {
		MediaUploadResponse mediaUploadResponse = new MediaUploadResponse();
		String url = String.format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s",
				accessToken, type);

		// http 请求头设置
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setSoTimeout(1000);
		PostMethod method = new PostMethod(url);
		method.setRequestHeader("Content-Type", "multipart/form-data");
		try {
			if (file != null && file.exists()) {
				FilePart filepart = new FilePart("media", file, "image/jpeg", "UTF-8");
				Part[] parts = new Part[] { filepart };
				MultipartRequestEntity entity = new MultipartRequestEntity(parts,
						method.getParams());
				method.setRequestEntity(entity);
				int status = client.executeMethod(method);
				if (status == HttpStatus.SC_OK) {
					String responseContent = method.getResponseBodyAsString();
					JsonParser jsonparer = new JsonParser();
					JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
					logger.debug("mediaUpload : {}", json);
					if (json.get("errcode") == null)
					{ 
						mediaUploadResponse.setMediaId( json.get("media_id").getAsString());
						mediaUploadResponse.setType( json.get("type").getAsString());
					}
				}
			}
		} catch (Exception e) {
			logger.error("mediaUpload 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"上传微信图片错误"));
		}
		return mediaUploadResponse;
	}

	@Override
	public GetLiveResponse getliveList(String accessToken, Integer start, Integer limit) {
		String url = String.format("https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=%s", accessToken);

		// http 请求头设置
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(1000);
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json");
		
        Map<String, Object> map = new HashMap<String, Object>();
		map.put("start", start);
		map.put("limit", limit);
		
        // 转换设置参数
        String jsonStr = JSONObject.toJSONString(map);
        RequestEntity requestEntity = new StringRequestEntity(jsonStr);
        method.setRequestEntity(requestEntity);

        try {
        	// 执行请求
            client.executeMethod(method);
            
            String responseStr = method.getResponseBodyAsString();
            logger.debug("getliveinfo : {}", responseStr);
            return objectMapper.readerFor(GetLiveResponse.class).readValue(responseStr);
		} catch (IOException e) {
			logger.error("getliveinfo 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"获取直播房间列表错误"));
		}
	}

	@Override
	public ReplayResponse getliveinfo(ReplayRequest request) {
		String url = String.format("https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=%s", request.getAccessToken());

		// http 请求头设置
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(1000);
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json");
		
        Map<String, Object> map = new HashMap<String, Object>();
		map.put("action", request.getAction());
		map.put("room_id", request.getRoomId());
		map.put("start", request.getStart());
		map.put("limit", request.getLimit());
		
        // 转换设置参数
        String jsonStr = JSONObject.toJSONString(map);
        RequestEntity requestEntity = new StringRequestEntity(jsonStr);
        method.setRequestEntity(requestEntity);

        try {
        	// 执行请求
            client.executeMethod(method);
            
            String responseStr = method.getResponseBodyAsString();
            logger.debug("getliveinfo : {}", responseStr);
            return objectMapper.readerFor(ReplayResponse.class).readValue(responseStr);
		} catch (IOException e) {
			logger.error("getliveinfo 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"获取直播间回放视频错误"));
		}
		
	}

	@Override
	public CreateRoomResponse createRoom(CreateRoomRequest request) {	
		String url = String.format("https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token=%s", request.getAccessToken());

        // http 请求头设置
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(10000);
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json");
		
        
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", request.getName());
		map.put("coverImg", request.getCoverImg());
		map.put("startTime", request.getStartTime());
		map.put("endTime", request.getEndTime());
		map.put("anchorName", request.getAnchorName());
		map.put("anchorWechat", request.getAnchorWechat());
		map.put("shareImg", request.getShareImg());
		map.put("feedsImg", request.getFeedsImg());
		map.put("type", request.getType());
		map.put("screenType", request.getScreenType());
		map.put("closeLike", request.getCloseLike());
		map.put("closeGoods", request.getCloseGoods());
		map.put("closeComment", request.getCloseComment());
		
        // 转换设置参数
        String jsonStr = JSONObject.toJSONString(map);
        RequestEntity requestEntity = new StringRequestEntity(jsonStr);
        method.setRequestEntity(requestEntity);

        try {
        	// 执行请求
            client.executeMethod(method);
            
            String responseStr = method.getResponseBodyAsString();
            logger.debug("createRoom : {}", responseStr);
            return objectMapper.readerFor(CreateRoomResponse.class).readValue(responseStr);
		} catch (IOException e) {
			logger.error("createRoom 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"创建直播间错误"));

		}
	}

	@Override
	public UniteResponse delRoom(String accessToken, String roomId) {
		String url = String.format("https://api.weixin.qq.com/wxaapi/broadcast/room/deleteroom?access_token==%s", accessToken);

		// http 请求头设置
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setSoTimeout(1000);
		PostMethod method = new PostMethod(url);
		method.setRequestHeader("Content-Type", "application/json");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", roomId);

		// 转换设置参数
		String jsonStr = JSONObject.toJSONString(map);
		RequestEntity requestEntity = new StringRequestEntity(jsonStr);
		method.setRequestEntity(requestEntity);

		try {
			// 执行请求
			client.executeMethod(method);

			String responseStr = method.getResponseBodyAsString();
			logger.debug("delRoom : {}", responseStr);
			return objectMapper.readerFor(UniteResponse.class).readValue(responseStr);
		} catch (IOException e) {
			logger.error("delRoom 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"删除房间错误"));
		}
	}

	@Override
	public GoodsAddResponse goodsAdd(GoodsAddRequest request) {
		String url = String.format("https://api.weixin.qq.com/wxaapi/broadcast/goods/add?access_token=%s", request.getAccessToken());

		// http 请求头设置
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(5000);
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json");
		
        Map<String, Object> map = new HashMap<String, Object>();
		map.put("goodsInfo", request.getGoodsInfo());
		
        // 转换设置参数
        String jsonStr = JSONObject.toJSONString(map);
        RequestEntity requestEntity = new StringRequestEntity(jsonStr);
        method.setRequestEntity(requestEntity);

        try {
        	// 执行请求
            client.executeMethod(method);
            
            String responseStr = method.getResponseBodyAsString();
            logger.debug("goodsAdd : {}", responseStr);
            return objectMapper.readerFor(GoodsAddResponse.class).readValue(responseStr);
		} catch (IOException e) {
			logger.error("goodsAdd 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"商品添加并提审错误"));

		}
	}

	@Override
	public UniteResponse goodsDelete(String accessToken, String goodsId) {
		String url = String.format("https://api.weixin.qq.com/wxaapi/broadcast/goods/delete?access_token=%s", accessToken);

		// http 请求头设置
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(1000);
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json");
		
        Map<String, Object> map = new HashMap<String, Object>();
		map.put("goodsId", goodsId);
		
        // 转换设置参数
        String jsonStr = JSONObject.toJSONString(map);
        RequestEntity requestEntity = new StringRequestEntity(jsonStr);
        method.setRequestEntity(requestEntity);

        try {
        	// 执行请求
            client.executeMethod(method);
            
            String responseStr = method.getResponseBodyAsString();
            logger.debug("goodsDelete : {}", responseStr);
            return objectMapper.readerFor(UniteResponse.class).readValue(responseStr);
		} catch (IOException e) {
			logger.error("goodsDelete 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"删除商品错误"));
		}
	}

	@Override
	public GetgoodswarehouseResponse getgoodswarehouse(String accessToken, List<String> goodsIds) {
		String url = String.format("https://api.weixin.qq.com/wxa/business/getgoodswarehouse?access_token=%s", accessToken);

		// http 请求头设置
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(1000);
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json");
		
        Map<String, Object> map = new HashMap<String, Object>();
		map.put("goods_ids", goodsIds);
		
        // 转换设置参数
        String jsonStr = JSONObject.toJSONString(map);
        RequestEntity requestEntity = new StringRequestEntity(jsonStr);
        method.setRequestEntity(requestEntity);

        try {
        	// 执行请求
            client.executeMethod(method);
            
            String responseStr = method.getResponseBodyAsString();
            logger.debug("getgoodswarehouse : {}", responseStr);
            return objectMapper.readerFor(GetgoodswarehouseResponse.class).readValue(responseStr);
		} catch (IOException e) {
			logger.error("getgoodswarehouse 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"获取商品信息错误"));
		}
		
	}

	@Override
	public GetgoodswarehouseResponse getapproved(String accessToken, Integer offset, Integer limit, Integer status) {
		String url = String.format("https://api.weixin.qq.com/wxaapi/broadcast/goods/getapproved?access_token=%s", accessToken);

		String text = client.get()
				.uri(b -> b.path(url).queryParam("offset", offset).queryParam("limit", limit)
						.queryParam("status", status).build())
				.accept(MediaType.APPLICATION_JSON_UTF8).exchange().flatMap(res -> res.bodyToMono(String.class))
				.block();
		logger.debug("createRoom 获取商品列表 : {}", text);
		try {
			return objectMapper.readerFor(GetgoodswarehouseResponse.class).readValue(text);
		} catch (IOException e) {
			logger.error("createRoom 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"获取商品列表错误"));
		}
	}

	@Override
	public UniteResponse roomAddgoods(String accessToken, List<String> ids, String roomId) {
		String url = String.format("https://api.weixin.qq.com/wxaapi/broadcast/room/addgoods?access_token=%s", accessToken);

		// http 请求头设置
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(1000);
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json");
		
        Map<String, Object> map = new HashMap<String, Object>();
		map.put("ids", ids);
		map.put("roomId", roomId);
		
        // 转换设置参数
        String jsonStr = JSONObject.toJSONString(map);
        RequestEntity requestEntity = new StringRequestEntity(jsonStr);
        method.setRequestEntity(requestEntity);

        try {
        	// 执行请求
            client.executeMethod(method);
            
            String responseStr = method.getResponseBodyAsString();
            logger.debug("roomAddgoods : {}", responseStr);
            return objectMapper.readerFor(UniteResponse.class).readValue(responseStr);
		} catch (IOException e) {
			logger.error("roomAddgoods 失败 : {}", e);
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),"往指定直播间导入已入库商品错误"));
		}
		
	}

}
